//
//  AppDelegate.swift
//  我的微博练习
//
//  Created by zhangguo on 15/10/8.
//  Copyright © 2015年 zhangguo. All rights reserved.
//

import UIKit

//通知
let GFRootViewCotrollerSwitchNotification = "GFRootViewCotrollerSwitchNotification"

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
      
        //注册通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector:  "switchViewController:", name: GFRootViewCotrollerSwitchNotification, object: nil)

        setUpperarance()
        
        window = UIWindow (frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor = UIColor.whiteColor()
        window?.rootViewController = defaultViewController()
        window?.makeKeyAndVisible()
        
        return true
    }
    
    //注销通知
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    //切换控制器
   func switchViewController(n:NSNotification){
        print("切换控制器 \(n)")

        let mainVC = n.object as! Bool
        window?.rootViewController = mainVC ? mainViewController() :WelcomeViewController()
    }
    //返回启动的默认控制器
    private func defaultViewController()->UIViewController{
//        没有登录 返回主控制
        if !UserAccount.userLogon{
            return mainViewController()
        }else{
            return isNewUpdate() ? NewFeatureCollectionViewController(): WelcomeViewController()
        }
    }
    /// 检查是否有新版本
    private func isNewUpdate() -> Bool {
        // 1. 获取程序当前的版本
        let currentVersion = Double(NSBundle.mainBundle().infoDictionary!["CFBundleShortVersionString"] as! String)!
        
        // 2. 获取程序`之前`的版本，偏好设置
        let sandboxVersionKey = "sandboxVersionKey"
        let sandboxVersion = NSUserDefaults.standardUserDefaults().doubleForKey(sandboxVersionKey)
        
        // 3. 将当前版本保存到偏好设置
        NSUserDefaults.standardUserDefaults().setDouble(currentVersion, forKey: sandboxVersionKey)
        // iOS 7.0 之后，就不需要同步了，iOS 6.0 之前，如果不同步不会第一时间写入沙盒
        NSUserDefaults.standardUserDefaults().synchronize()
        
        // 4. 返回比较结果
        return currentVersion > sandboxVersion
    }

//设置外观
    private func setUpperarance(){
        UINavigationBar.appearance().tintColor = UIColor.orangeColor()
        UITabBar.appearance().tintColor = UIColor.orangeColor()
    }
}

